using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace IWS.SiteManager.Web.Controllers
{
	public class ContentController : Controller
	{
		Core.Model.ContentRepository _ContentService;

		public ContentController()
			: base()
		{
			_ContentService = new IWS.SiteManager.Core.Model.ContentRepository();
			SetMasterPage("Default");
		}
		public ContentController(Core.Model.ContentRepository service) : base()
		{
			_ContentService = service;
		}

		public ActionResult ViewByPermalink(string section, string permalink)
		{
			SetMasterPage(section);
			Core.Model.Content page = null;

			if (string.IsNullOrEmpty(permalink))
			{
				//lookup default page for section. 
				page = _ContentService.GetIndexPage(section);
			}
			else
			{
				if (!string.IsNullOrEmpty(permalink))
					page = _ContentService.GetPage(section, permalink.Trim().ToLower());
			}

			if (page == null)
			{
				return RedirectToAction("PageNotFound", new { section= section, permalink=permalink});
			}
			else
			{
				ViewData.Model = page;
				ViewData[Core.Constants.ViewDataTitle] = page.Title;
			}
			return View();
		}

		public ActionResult Index()
		{
			string section = _ContentService.GetDefaultSection();
			return RedirectToAction("ViewByPermalink", "Content", new { section=section, permalink=string.Empty });
		}

		void SetMasterPage(string section)
		{
			string master_file_vpath = string.Format(Core.Constants.SiteMasterLocationFormatString, section);

			if (Server != null)
			{
				if (System.IO.File.Exists(Server.MapPath(master_file_vpath)))
					ViewData[Core.Constants.ViewDataMasterPageFile] = master_file_vpath;
			}
			else //prob default constructor. do it anyway for default.
				ViewData[Core.Constants.ViewDataMasterPageFile] = master_file_vpath;
		}

		public ViewResult Periodical()
		{
			throw new NotImplementedException();
		}
		public ViewResult PageNotFound(string section, string permalink)
		{
			ViewData["section"] = section;
			ViewData["permalink"] = permalink;

			return View();
		}
	}
}
